package main

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "go.uber.org/zap"
    "google.golang.org/protobuf/proto"
    "google.golang.org/protobuf/reflect/protoreflect"
    "google.golang.org/protobuf/reflect/protoregistry"
    "laxkits/lib/laxmysql"
    "laxkits/lib/laxutils"
    "laxkits/lib/zlogger"
    _ "laxkits/lib/ropb"
)

type XMLNode struct {
    Log zlogger.LaxLogNode `xml:"log"`
    Mysql []laxmysql.LaxMySQLConfig `xml:"mysqlgroup>mysql"`
    RoleId int64 `xml:"role_id"`
    FieldName string `xml:"field_name"`
}
var xmlconfig  XMLNode


func main() {
    if err := laxutils.LoadXmlFile("conf.xml", &xmlconfig); err != nil {
        fmt.Println("读取xml失败")
        return
    }
    zlogger.InitLogger(&xmlconfig.Log)
    if err := laxmysql.GetLaxMySQLMgr().RegisterByConfig(xmlconfig.Mysql); err != nil {
        zap.S().Errorf("mysql注册失败:%s", err)
        return
    }
    defer laxmysql.GetLaxMySQLMgr().CloseAll()

    fieldRefType, err := protoregistry.GlobalTypes.FindMessageByName(protoreflect.FullName("KKSG." + xmlconfig.FieldName))
    if err != nil {
        zap.S().Errorf("查找field:[%s]对应的KKSG结构失败:%s", xmlconfig.FieldName, err)
        return
    }
    qsql := fmt.Sprintf("select id, name, account, %s from player%d.role where id = ?", xmlconfig.FieldName, xmlconfig.RoleId % 5)
    laxmysql.GetLaxMySQLMgr().Foreach(func(conn *laxmysql.LaxMySQLConn) {
        if conn == nil {
            return
        }
        if err = conn.LaxQueryRow(qsql, func(row *sql.Row) error {
            var id int64
            var name, account string
            var queryField []byte
            if err = row.Scan(&id, &name, &account, &queryField); err != nil {
                return err
            }
            fieldEntity := fieldRefType.New().Interface()
            if err = proto.Unmarshal(queryField, fieldEntity); err == nil {
                if jsonValue, err := json.MarshalIndent(fieldEntity, "", "    "); err == nil {
                    zap.S().Infof("在mysql[%s] 查找到角色:%d,%s,%s,结果:\n %s",
                        conn.GetId(),
                        id,
                        name,
                        account,
                        jsonValue)
                }
            }
            return nil
        }, xmlconfig.RoleId) ; err != nil {
            zap.S().Warn("出错", err)
        }
    }, false)
}
